<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>工具插件下载</title>
  <link crossorigin="" rel="icon" type="image/x-icon" href="./favicon.ico">
  <link rel="stylesheet" type="text/css" href="./dist/index.css">
  <link rel="stylesheet" type="text/css" href="./dist/tooltip.min.css">
  <script src="./dist/jquery.min.js"></script>
  <link href="//unpkg.com/layui@2.7.6/dist/css/layui.css" rel="stylesheet">
  <script src="//unpkg.com/layui@2.7.6/dist/layui.js"></script>
</head>

<body>
  <button class="layui-btn layui-btn-primary layui-border-green add" onclick="clickFn()"><i class="layui-icon layui-icon-add-circle"></i>增加</button> 
  <button class="layui-btn layui-btn-primary layui-border-blue reload" onclick="getdata()"><i class="layui-icon layui-icon-refresh"></i>刷新</button>
  <button class="layui-btn layui-btn-primary layui-border-red del" onclick="deldata()"><i class="layui-icon layui-icon-delete"></i>删除</button>
  <!-- 列表 -->
  <div class="body">
    <div class="main">
      <ul id="list"></ul>
    </div>
  </div>

  <!-- tooltips 容器 -->
  <div class="tooltip-container no-display" id="tooltipText"></div>

  <script>

    //设置gitee参数 
    const git_url = 'https://gitee.com/api'
    const header = { 'Content-type': 'application/json;charset=UTF-8' }
    const git_key = ['access_token', 'owner', 'repo', 'version']
    const initext = 'ZGQK'
    const owner = 'yuanfang289'
    const repo = 'download'
    const path = 'data'
    const access_token = '0b70f12131f3aad73fe3d6e6e80529c8'


    // 设置数据源
    var downlist = []
    var commit = '更新'

    // 渲染dom
    function render(){
      let html = ``
      for (let i = 0; i < downlist.length; i++) {
        let item = downlist[i]
        html += `  <li class="item" data-id="${item.id}" ondblclick="ondblClick(${i})">
          <div class="icon">
            <img src="${item.icon}">
          </div>
            <div class="name ellipsis">${item.name}</div>
            <div class="desc ellipsis">
              ${item.desc}
            </div>
          <a class="btn" href="${item.url}" download="w3logo">下载</a>
          <span class="sort">${i+1}</span>
        </li>`
      }
      document.getElementById('list').innerHTML = html
      checkEllipsis()
    }

    function deldata(){
      layer.prompt({title: '序号', formType: 3}, function(seq, index){
        layer.close(index);
        layer.prompt({title: '密令', formType: 1}, function(pass, index){
          downlist.splice(seq-1,1)
          commit = '删除'
          render()
          updata()
          layer.close(index);
        });
      });
    }

    function ondblClick(idx){
      // downlist.splice(idx,1)
      clickFn('edit',idx)
    }
    // tooltips提示
    function tooltip(){
      "use strict"; let t, e, o, i; 
      var n = {
        create: function (t, n) { e = n.getBoundingClientRect(), i = e.top + e.height, o = document.createTextNode(n.getAttribute("data-tooltip")), t.appendChild(o), e.left > window.innerWidth - 100 ? t.className = "tooltip-container tooltip-left" : e.left + e.width / 2 < 100 ? t.className = "tooltip-container tooltip-right" : t.className = "tooltip-container tooltip-center" }, 
        position: function (t, o) {
          const n = window.innerWidth - 100, l = e.left + e.width / 2 - t.offsetWidth / 2; e.left > n && e.width < 50 ? (t.style.left = e.left - (t.offsetWidth + e.width) + "px",
            t.style.top = o.offsetTop + "px") : e.left > n && e.width > 50 ? (t.style.left = e.left - t.offsetWidth - 20 + "px", t.style.top = o.offsetTop + "px") : e.left + e.width / 2 < 100 ? (t.className = "tooltip-container tooltip-right", t.style.left = e.left + e.width + 20 + "px", t.style.top = o.offsetTop + "px") : i + 10 + t.offsetHeight > window.innerHeight ? (t.className = "tooltip-container tooltip-center-bottom", t.style.left = l + "px", t.style.top = i - t.offsetHeight - 35 + window.scrollY + "px") : (t.style.left = l + "px", t.style.top = i + 10 + window.scrollY + "px")
        }
      }; 
      function l(e) {
        const o = Object.create(n), i = e.currentTarget; t.setAttribute("aria-hidden", !1), o.create(t, i),
          o.position(t, i)
      } 
      function r(e) { const o = Object.create(n), i = e.currentTarget; t.setAttribute("aria-hidden", !1), "9" == e.keyCode && (t.firstChild && (t.removeChild(t.firstChild), t.removeAttribute("style")), o.create(t, i), o.position(t, i)) } 
      function d() { a() } 
      function s(t) { "27" == t.keyCode && a() } 
      function c(t) { t.target.hasAttribute("data-tooltip") || a() } 
      function a() { t.setAttribute("aria-hidden", !0), t.className = "tooltip-container no-display", t.textContent = "", t.removeAttribute("style") } 
      (function () {
        t = document.documentElement.querySelector(".tooltip-container"); 
        const ee = document.documentElement.querySelectorAll("[data-tooltip]"); 
        Array.prototype.forEach.call(ee, (function (t) { t.addEventListener("mouseover", l), 
        t.addEventListener("mouseout", d), 
        t.addEventListener("keyup", r), 
        t.addEventListener("keyup", s) })), 
        t && (document.addEventListener("keyup", s), 
        document.addEventListener("click", c))
      })()
    }

    // dom检查 给有省略号的dom设置属性 data-tooltip
    function checkEllipsis(){
      let doms = document.getElementsByClassName('ellipsis')
      for (let i = 0; i < doms.length; i++) {
        let this_ = doms[i]
        if (this_.scrollHeight > this_.clientHeight) {
          this_.setAttribute('data-tooltip', this_.innerHTML);
        } else {
          if (this_.scrollWidth > this_.offsetWidth) {
            this_.setAttribute('data-tooltip', this_.innerHTML);
          }
        }
      }
    }

    // 节流函数
    function throttle(func, wait) {
      var context, args, timeout;
      return function () {
        context = this;
        args = arguments;
        if (!timeout) {
          timeout = setTimeout(function () {
            func.apply(context, args);
            timeout = null;
          }, wait);
        }
      }
    }
    // 删除占位节点
    function removeKong() {
      let len = document.getElementsByClassName('kong').length
      if (len > 0) {
        for (let i = 0; i < len; i++) {
          document.getElementsByClassName('kong')[0].remove()
        }
      }
    }
    // 视图变化更新占位节点
    function handle() {
      let a = document.getElementById('list').clientHeight
      if (a >= 500) {//多行
        let num = parseInt(document.getElementById('list').clientWidth / 250)
        let total = document.getElementsByClassName('item').length
        let kong = num - (total % num)
        if (total % num != 0) {
          let child = ``
          for (let i = 0; i < kong; i++) {
            child += `<li style="visibility: hidden;width:250px;" class="kong"></li>`
          }
          removeKong()
          document.getElementById('list').appendChild(document.createRange().createContextualFragment(child))
        }
      } else {//单行
        removeKong()
      }
    }
    //增加数据
    function clickFn(type,idx) {
      var index = layer.open({
        type: 1,
        title: false,
        closeBtn: 0,
        shadeClose: true,
        skin: 'yourclass',
        content: `<form class="layui-form" action="" lay-filter="example">
        <div class="layui-form-item">
          <label class="layui-form-label">标题</label>
          <div class="layui-input-block">
            <input type="text" name="name" lay-verify="required" autocomplete="off" placeholder="请输入标题" class="layui-input" id="validate-name">
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">URL</label>
          <div class="layui-input-block">
            <input type="text" name="url" lay-verify="required" autocomplete="off" placeholder="请输入URL" class="layui-input" id="validate-url">
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">ICON</label>
          <div class="layui-input-block">
            <input type="text" name="icon" lay-verify="required" placeholder="请输入ICON" autocomplete="off" class="layui-input" id="validate-icon">
          </div>
        </div>
        <div class="layui-form-item layui-form-text">
          <label class="layui-form-label">介绍</label>
          <div class="layui-input-block">
            <textarea placeholder="请输入介绍内容" class="layui-textarea" name="desc" lay-verify="required" id="validate-desc"></textarea>
          </div>
        </div>
      
        <div class="layui-form-item">
          <div class="layui-input-block">
            <button type="button" class="layui-btn" id="LAY-component-form-getval" lay-filter="demo1">${type=='edit'?'更新':'立即提交'}</button>
          </div>
        </div>
      </form>`,
        success: function () {
          // 表单
          layui.use(function () {
            var $ = layui.$;
            var form = layui.form;
            var layer = layui.layer;
            if(type=='edit'){//赋值
              form.val('example', downlist[idx]);
            }
            $('#LAY-component-form-getval').on('click', function () {
              var isValidDesc = form.validate('#validate-desc');
              var isValidIcon = form.validate('#validate-icon');
              var isValidUrl = form.validate('#validate-url');
              var isValidName = form.validate('#validate-name');
              if(isValidName && isValidUrl && isValidIcon && isValidDesc){
                var data = form.val('example');
                if(type == 'edit'){
                  data.id = downlist[idx].id
                  downlist[idx] = data
                }else{
                  data.id = downlist.length+1
                  downlist.push(data)
                }
                render()
                updata()
                layer.close(index);
              }
            });
          });
        }
      },);
    }

    //获取数据方法
    function getdata() {
      var loadIndex = layer.msg('加载中', {
        icon: 16,
        shade: 0.1
      });;
      let url = git_url + '/v5/repos/' + owner + '/' + repo + '/contents/' + path + '?access_token=' + access_token
      fetch(url, {
        method: 'GET',
        headers: header
      }).then(res => res.json())
        .catch((error) => {
          layer.close(loadIndex)
        })
        .then((resp) => {
          layer.close(loadIndex)
          downlist = JSON.parse(decodeURIComponent(window.atob(resp['content'])))
          render()
        })
    }

    //获取更新数据需要的sha
    function updata() {
      let url = git_url + '/v5/repos/' + owner + '/' + repo + '/contents/' + path + '?access_token=' + access_token
      fetch(url, {
        method: 'GET',
        headers: header
      }).then(res => res.json())
        .catch((error) => {

        })
        .then((resp) => {
          updateTagsSha(resp.sha)
        })
    }

    //更新数据上传gitee
    function updateTagsSha(sha, message = commit) {
      let data = {
        "access_token": access_token,
        "content": window.btoa(encodeURIComponent(JSON.stringify(downlist))),
        "sha": sha,
        "message": message
      }
      let put_url = git_url + '/v5/repos/' + owner + '/' + repo + '/contents/' + path
      fetch(put_url, {
        method: 'PUT',
        body: JSON.stringify(data),
        headers: header
      }).then(res => res.json())
        .catch((error) => {
          commit = '更新'
        })
        .then((resp) => {
          commit = '更新'
        })
    }

    // 获取需要监听的dom区域
    const targetNode = document.getElementById('list');
    // 观察器的配置（需要观察什么变动）
    const config = { attributes: true, childList: true, subtree: true };
    // 创建一个观察器实例并传入回调函数
    const observer = new MutationObserver(tooltip);
    // 以上述配置开始观察目标节点
    observer.observe(targetNode, config);

    // 初始化数据
    getdata()

  </script>
</body>

</html>